package xyz.yuzegod.megawalls.timer;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import xyz.yuzegod.megawalls.game.GamePlayer;
import xyz.yuzegod.megawalls.spectator.SpectatorSettings;

public class ObjectiveTimer implements Runnable
{
    @Override
    public void run() {
        for (final Player p : Bukkit.getOnlinePlayers()) {
            final GamePlayer gamePlayer = GamePlayer.get(p.getUniqueId());
            int i = 0;
            for (final Player player : Bukkit.getOnlinePlayers()) {
                final int health = (int)player.getHealth();
                Objective obj = p.getScoreboard().getObjective(DisplaySlot.BELOW_NAME);
                if (obj == null) {
                    obj = p.getScoreboard().registerNewObjective(String.valueOf(System.currentTimeMillis() + i), "health");
                    obj.setDisplaySlot(DisplaySlot.BELOW_NAME);
                    obj.setDisplayName(ChatColor.RED + "❤");
                }
                obj.setDisplayName(ChatColor.RED + "❤");
                obj.getScore((OfflinePlayer)player).setScore(health);
                ++i;
                obj = p.getScoreboard().getObjective(DisplaySlot.PLAYER_LIST);
                if (obj == null) {
                    obj = p.getScoreboard().registerNewObjective(String.valueOf(System.currentTimeMillis() + i), "dummy");
                    obj.setDisplaySlot(DisplaySlot.PLAYER_LIST);
                }
                obj.getScore((OfflinePlayer)player).setScore(health);
                ++i;
                final GamePlayer otherPlayer = GamePlayer.get(player.getUniqueId());
                if (gamePlayer.isSpectator() && otherPlayer.isSpectator()) {
                    if (SpectatorSettings.get(gamePlayer).getOption(SpectatorSettings.Option.HIDEOTHER)) {
                        p.hidePlayer(player);
                    }
                    else {
                        p.showPlayer(player);
                    }
                }
                else if (!gamePlayer.isSpectator() && otherPlayer.isSpectator()) {
                    p.hidePlayer(player);
                }
                else if (gamePlayer.isSpectator() && !otherPlayer.isSpectator()) {
                    player.hidePlayer(p);
                }
                else {
                    if (gamePlayer.isSpectator() || otherPlayer.isSpectator()) {
                        continue;
                    }
                    p.showPlayer(player);
                }
            }
        }
    }
}
